<?php

/**
 * @Author: king
 * @Date:   2019-05-04 17:11:01
 * @Last Modified by:   king
 * @Last Modified time: 2019-06-05 21:41:59
 */
namespace App\Models\Api;
use App\Exceptions\ApiException;
use App\Models\Api\Base;
use App\Models\Api\Recode;
use AstroTool\Cache\CacheManage;
use Cache;

class LanmeiCounselorProblemRecode extends Base
{
    protected $table = 'counselor_problem_recode';
    protected $dateFormat = 'U';
    public $guarded       = [];
    const CREATED_AT      = 'create_time';
    const UPDATED_AT      = 'update_time';
    public $timestamps    = false;

    /**
     * 档案备份
     * @param array $rids
     * @return array
     * @throws ApiException
     */
    public function copeRecode(array $rids)
    {
        try
        {
            $recodeDataModels = Recode::whereIn('id', $rids)
            ->get(['uid','aid','isself','name','type','year','month','day','hour','minute','timezone','birth_country','birth_province','birth_city','live_country','live_province','live_city','comments','long_deg','long_min','ew','lat_deg','lat_min','ns','is_summer','avatar','from','or_day'])->toArray();
            //判断档案信息是否有效
            if (count($rids) !== count($recodeDataModels))
            {
                throw new ApiException('档案数据异常', 0);
            }

            $recodeData = [];
            foreach ($recodeDataModels as $recodeDataModelItem)
            {
                array_push($recodeData, $recodeDataModelItem);
            }

            $resultModels = $this->saveAll($recodeData);

        }
        catch (Exception $e)
        {
            throw new ApiException('服务异常', 0);
        }

        $recodeIds = [];
        foreach ($resultModels as $recodeModeItem)
        { 

            array_push($recodeIds, $recodeModeItem->id);
        }

        return $recodeIds;
    }

    /**
     * 批量获取问答 档案信息
     * @param $rids array|string
     * @param array $field
     * @return array
     * @throws \Exception
     */
    public function batchGetRecordInfoByIds($rids, $field = [])
    {
        $rids = is_array($rids) ? $rids : explode(',', $rids);

        $data = CacheManage::getInstance()->setCacheConfig('counselor_problem_record')
            ->batchGetCache($rids, function ($ids)
            {
                return $this->batchGetRecordDataByIds($ids);
            }, $field, 'list_details');

        return $data;
    }

    /**
     * 批量获取档案信息-->通过数据库
     * @param $ids
     * @return array
     * @throws ApiException
     */
    protected function batchGetRecordDataByIds($ids)
    {
        try
        {
            $data = $this->whereIn('id', $ids)->get(['id','uid','aid','isself','name','type','year','month','day','hour','minute','timezone','birth_country','birth_province','birth_city','live_country','live_province','live_city','comments','long_deg','long_min','ew','lat_deg','lat_min','ns','is_summer','avatar','from','or_day'])->keyBy('id')->toArray();
          foreach ($data as $k => $v)
            {
                if ($v['or_day'] == 0)
                {
                    $data[$k]['day'] = $v['day'];
                }
            }
        }
        catch (Exception $e)
        {
            throw new ApiException('服务异常', 200, config('code.error'));
        }

        return $data;
    }

    /**
     * 获取问题确认档案信息
     * @param $recodeIds
     * @return array
     * @throws \Exception
     */
    public function getCreateProblemRecode($recodeIds): array
    {
        $recodeData = $this->batchGetRecordInfoByIds($recodeIds, 'id,name,year,month,day,hour,minute,timezone,birth_country,birth_province,birth_city,live_country,live_province,live_city');

        $recodeInfo = [];
        foreach ($recodeData as $recodeItem)
        {
           
            // 出生地址
            $birthAddress = $recodeItem['birth_country'] . ' ' . $recodeItem['birth_province'] . ' ' . $recodeItem['birth_city'];
            // 现居地址
            $liveAddress = $recodeItem['live_country'] . ' ' . $recodeItem['live_province'] . ' ' . $recodeItem['live_city'];
            // 出生日期
            $birthTime = $recodeItem['year'] . '-' . sprintf("%02d", $recodeItem['month']) . '-' . sprintf("%02d", $recodeItem['day']) . ' ' . sprintf("%02d", $recodeItem['hour']) . ':' . sprintf("%02d", $recodeItem['minute']);

            $recodeInfo[] = [
                'name' => $recodeItem['name'],
                'birth_address' => $birthAddress,
                'live_address' => $liveAddress,
                'rid' => $recodeItem['id'],
                'birth_time' => $birthTime,
            ];
        }

        return $recodeInfo;
    }

    /**
     * 批量获取档案名称
     * @param string|array $rids 12,13,14 | [12,13,14]
     * @return array
     * @throws \Exception
     */
    public function getProblemRecodeName($rids)
    {
        $rdata = $this->batchGetRecordInfoByIds($rids, 'id,name');

        $resultData = [];
        foreach ($rdata as $rdataItem)
        {
            $resultData[$rdataItem['id']] = [
                'rid' => $rdataItem['id'],
                'name' => $rdataItem['name'],
            ];
        }

        return $resultData;
    }
    /**
     * 保存多个数据到当前数据对象
     * @access public
     * @param array     $dataSet 数据
     * @param boolean   $replace 是否自动识别更新和写入
     * @return array|false
     */
    public function saveAll($dataSet, $replace = true)
    {

        $result = [];
        \DB::beginTransaction();
        try {
            $pk = 'id';
            if (is_string($pk) && $replace) {
                $auto = true;
            }
            foreach ($dataSet as $key => $data) {
                if (!empty($auto) && isset($data[$pk])) {
                    $result[$key] = self::update($data);
                } else {
                    $result[$key] = self::create($data);
                }
            }
            \DB::commit();
            return $result;
        } catch (\Exception $e) {
            \DB::rollback();
            throw $e;
        }
    }

}
